# -*- coding: utf-8 -*-

from conveyor import Conveyor
from aws import AwsServiceResource


class AwsSqs(Conveyor, AwsServiceResource):

    def _init(self):
        super(AwsSqs, self)._init('sqs')

    def get_queue(self, name):
        queue = None

        try:
            queue = self.resource.get_queue_by_name(QueueName=name)
        except Exception as e:
            if e.message.find('AWS.SimpleQueueService.NonExistentQueue') > -1:
                if 'allow_create' in self._cfg and self._cfg['allow_create']:
                    attributes = self._cfg['queue_attributes'] if 'queue_attributes' in self._cfg else {}
                    self.resource.create_queue(QueueName=name, Attributes=attributes)
                    queue = self.resource.get_queue_by_name(QueueName=name)

            if not queue:
                raise e

        return queue

    def send(self, data):
        if 'queue_used_for_send' not in self._cfg:
            raise Exception('AwsSqs.send: [queue_used_for_send] not configured.')

        res = self.get_queue(self._cfg['queue_used_for_send']).send_message(MessageBody=data)

        return (res.get('MessageId'), res.get('MD5OfMessageBody'))

    def receive(self, ack_auto=True):
        if 'queue_used_for_receive' not in self._cfg:
            raise Exception('AwsSqs.receive: [queue_used_for_receive] not configured.')

        receive_args = self._cfg['receive_args'] if 'receive_args' in self._cfg else {}
        messages = []
        for x in self.get_queue(self._cfg['queue_used_for_receive']).receive_messages(**receive_args):
            messages.append(x.body)

            if ack_auto:
                x.delete()

        return messages

    def ack(self, data):
        super(AwsSqs, self).ack(data)
